from helper import *

class ipl_helper(geo_helper):
	def __init__(self):
		geo_helper.__init__(self)
		self.desc = \
			('continent', 'country', 'state', 'city', 'district', 'owner')
		self.ir = ([4,5, GL_CONTINENT], [2,3, GL_COUNTRY], \
			[7,8, GL_STATE], [11,-1, GL_CITY], [10,-1, GL_DISTRICT], \
			[9,-1, GL_OWNER])
		self.cir = []
	
	def readline(self, line, ir):
		rec = line.split(',')
		try:
			self.loc.clear()
			info = self.loc.info
			for n, d, flag in ir:
				desc = ''
				if d != -1:
					desc = rec[d][1:-1]
				info.append([rec[n][1:-1], desc, flag, 0, None])

			self.loc.range = (rec[0][1:-1], rec[1][1:-1])
			self.loc.coord = (rec[12][1:-1], rec[13][1:-1])
		except IndexError:
			return False
		return True
	
	def learn(self, line):
		return self.readline(line, self.ir)
	def read(self, line):
		return self.readline(line, self.cir)

class ipl_helper_cli(ipl_helper):
	def __init__(self):
		ipl_helper.__init__(self)
		self.sum_asked = 0
		
	def wizard(self):
		stop = 0
		print 'Please select field, q to quit'
		while not stop:
			rgcnt = 0
			for i, desc in enumerate(self.desc):
				if self.ir[i] not in self.cir:
					print '  '+str(i+1)+'. '+desc
					rgcnt += 1
			if rgcnt:
				s = raw_input('choice:')
				f = s.split(',')
				ncnt = 0
				fields = []
				for j in f:
					if not j in fields:
						try:
							n = int(j)
							ncnt += 1
						except ValueError:
							pass
						fields.append(j)
				if ncnt > 1:
					stop = 1
				for field in fields:
					if field == 'q':
						if not len(self.cir):
							for x in self.ir:
								self.cir.append(x)
						stop = 1
						break
					else:
						try:
							self.cir.append(self.ir[int(field)-1])
						except (IndexError, ValueError):
							continue
			else:
				stop = 1
		tip = 'Please select action, <cr> to ask\n  '
		answer = (OP_ALL, OP_ASK, OP_NON)
		return self.cli.ask(tip, answer)
	
	def check(self, line):
		s = raw_input('Is it IPligence Database (y/n)?')
		return self.cli.check(line)
	def ask(self, index):
		loc = self.loc
		path = loc.path(index)
		name, desc, t_flag, t_op, t_geo = loc.info[index]
		if desc == '':
			desc = name
		s = 'Detected new location['+desc+']: '+path+'\n  '
		answer = (OP_ALL, OP_AGN, OP_IGN, OP_ASK, OP_SKP, OP_NON)
		return self.cli.ask(s, answer), name
		
	def read(self, line):
		return ipl_helper.read(self, line)

